<template>
    <div class="app-container">
        <el-card shadow="always">
            <el-form :model="queryParams" :inline="true" label-width="100px">
                <el-form-item label="网络制式：" prop="networkType">
                    <el-select v-model="queryParams.networkType" placeholder="请选择网络制式" style="width: 240px">
                        <el-option v-for="dict in nhp_network_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属区县：" prop="county">
                    <el-select v-model="queryParams.county" placeholder="请选择所属区县" clearable style="width: 240px">
                        <el-option v-for="dict in nhp_county_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="站号" prop="stationNo">
                    <el-input v-model="queryParams.stationNo" placeholder="请输入站号" clearable style="width: 240px" />
                </el-form-item>
                <el-form-item label="基站名称：" prop="stationName">
                    <el-input v-model="queryParams.stationName" placeholder="请输入基站名称" clearable style="width: 240px" />
                </el-form-item>
                <el-form-item label="创建时间：" prop="createTime">
                    <el-date-picker v-model="queryParams.createStartEnd" type="daterange" range-separator="To"
                        start-placeholder="开始时间" end-placeholder="结束时间" :size="size" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="listAlarmTable">查询</el-button>
                    <el-button @click="unsetQueryForm"><el-icon>
                            <RefreshRight />
                        </el-icon>重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card shadow="always" style="margin-top: 10px;min-height: 500px;padding-bottom: 20px;">
            <el-row>
                <el-button type="primary" icon="Download" @click="exportData">导出</el-button>
            </el-row>
            <div id="table" style="margin-top: 20px;">
                <el-table v-loading="loading" ref="alarmTable" :data="tableData" style="width: 100%" @sort-change="sortChange" @filter-change="filterChange">
                    <el-table-column prop="county" label="所属区县" width="120" align="center" fixed />
                    <el-table-column prop="stationNo" label="站号" width="150" align="center" fixed />
                    <el-table-column prop="stationName" label="基站名称" width="420" align="center" fixed />
                    
                    <el-table-column prop="status" label="状态" width="150" align="center" fixed
                        :filter-multiple="false"
                        :filters="[
                            { text: '正常', value: 1 },
                            { text: '异常', value: 2 },
                        ] " 
                        :column-key="'status'"
                        filter-placement="bottom-end">
                        <template #default="scope">
                            <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'" disable-transitions>{{scope.row.status == 1 ? "正常" : "异常" }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建日期" :formatter="dateFormatter" width="150" fixed="right"
                        align="center" />
                    <el-table-column prop="alarmScore" label="故障告警总分" width="150" fixed="right" align="center" sortable="custom" />
                    <el-table-column fixed="right" label="操作" min-width="250" align="center">
                        <template #default="scope">
                            <el-button link type="primary" size="small"
                                @click="showAlarmDialog(scope.row.stationNo)">关联告警</el-button>
                            <el-button link type="primary" size="small"
                                @click="showDetailDialog(scope.row.stationNo)">详情</el-button>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <el-empty :image-size="40" />
                    </template>
                </el-table>
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 50, 100, 200]" :small="small" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next" :total="total" @size-change="listAlarmTable"
                    @current-change="listAlarmTable" />
            </div>
        </el-card>

        <el-dialog v-model="alarmDialogTableVisible" title="站点相关告警" width="1200"  @closed="closeAlarmDialog">
            <el-card style="margin-bottom: 15px;">
                <div style="display: flex">
                    <div class="card-left">
                        <div class="title-name">实时告警等级占比:</div>
                        <div
                          id="chart1"
                          style="width: 520px; height: 240px; margin: -10px 10px 10px 10px"
                          class=""
                          ref="chart1"
                          v-show="!showAll"
                        ></div>
                    </div>
                    <div class="card-right">
                        <div class="title-name">过去十日告警等级占比:</div>
                        <div
                          id="chart2"
                          style="width: 520px; height: 240px; margin: -10px 10px 10px 10px"
                          class=""
                          ref="chart2"
                          v-show="!showAll"
                        ></div>
                    </div>
                </div>
            </el-card>
            <el-tabs v-model="activeName">
                <el-tab-pane label="实时告警" name="realTimeAlarm">
                    <el-table v-loading="loading" ref="realTimeAlarmTable" :data="realTimeAlarmTableData"
                        style="width: 100% ; margin-bottom: 10px;">
                        <el-table-column prop="alarmId" label="告警id" width="200" align="center" />
                        <el-table-column prop="alarmTitle" label="告警标题" width="200" align="center" />
                        <el-table-column prop="eventTime" label="发生时间" width="200" align="center" />
                        <el-table-column prop="alarmStatus" label="告警状态" width="100" align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.alarmStatus == 1 ? 'success' : 'danger'" disable-transitions>{{scope.row.alarmStatus == 1 ? "正常" : "异常" }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="alarmLevel" label="告警等级" width="100" align="center" >
                            <template #default="scope">
                                 <el-tag :type="fnalarmLevel(scope.row.alarmLevel)" disable-transitions>{{scope.row.alarmLevel}}</el-tag>
                             </template>
                         </el-table-column>
                        <el-table-column prop="equipmentManufacturerName" label="厂商名称" width="200" align="center" />
                        <el-table-column prop="neName" label="网元名称" width="200" align="center" />
                        <el-table-column prop="standardId" label="标准告警号" width="200" align="center" />
                    </el-table>
                    <el-pagination v-model:current-page="realCurrentPage" v-model:page-size="realPageSize"
                        :page-sizes="[10, 50, 100, 200]" :small="small" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next" :total="realTotal" @size-change="listAlarmTable"
                        @current-change="listAlarmTable" />
                </el-tab-pane>
                <el-tab-pane label="过去十日历史告警" name="historyAlarm">
                    <el-table v-loading="loading" ref="historyAlarmTable" :data="historyAlarmTableData"
                        style="width: 100%; margin-bottom: 10px;">
                        <el-table-column prop="alarmId" label="告警id" width="200" align="center" fixed />
                        <el-table-column prop="alarmTitle" label="告警标题" width="300" align="center" fixed />
                        <el-table-column prop="eventTime" label="发生时间" width="200" align="center" fixed />
                        <el-table-column prop="recoveryTime" label="恢复时间" width="200" align="center" fixed />
                        <el-table-column prop="alarmStatus" label="告警状态" width="100" align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.alarmStatus == 1 ? 'success' : 'danger'" disable-transitions>{{scope.row.alarmStatus == 1 ? "正常" : "异常" }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="alarmLevel" label="告警等级" width="100" align="center" >
                            <template #default="scope">
                                 <el-tag :type="fnalarmLevel(scope.row.alarmLevel)" disable-transitions>{{scope.row.alarmLevel}}</el-tag>
                             </template>
                         </el-table-column>
                        <el-table-column prop="equipmentManufacturerName" label="厂商名称" width="200" align="center" />
                        <el-table-column prop="neName" label="网元名称" width="200" align="center" />
                        <el-table-column prop="standardId" label="标准告警号" width="200" align="center" />
                    </el-table>
                    <el-pagination v-model:current-page="historyCurrentPage" v-model:page-size="historyPageSize"
                        :page-sizes="[10, 50, 100, 200]" :small="small" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next" :total="historyTotal" @size-change="listAlarmTable"
                        @current-change="listAlarmTable" />
                </el-tab-pane>
            </el-tabs>
        </el-dialog>

        <el-dialog v-model="detailTableVisible" title="故障告警详情" width="1400" @opened="initLineChart" @closed="closeDetailDialog">
            <el-card class="card-box">
                <el-form :model="queryParams" ref="queryForm" :inline="true">
                    <el-form-item label="时间选择">
                      <el-date-picker
                        v-model="detailDatePicker"
                        type="daterange"
                        style="width: 350px"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        align="right"
                        @change="search"
                      ></el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="detailSearch">查询</el-button>        
                    </el-form-item>
                  </el-form>
                  <div class="card-content" style="display: flex" v-show="!showAll">
                    <div class="card-left">
                      <el-table
                        :data="detailData"
                        style="width: 100%"
                        class="tableBox"
                        max-height="500"
                        id="tableBox"
                        @row-click="handleClickChange"
                        :row-class-name="tableRowClassName"
                      >
                        <el-table-column prop="county" label="所属区县" width="120" align="center"  />
                        <el-table-column prop="stationNo" label="站号" width="150" align="center"  />
                        <el-table-column prop="stationName" label="基站名称" width="250" align="center" />
                        <el-table-column prop="createTime" label="创建时间" width="200" align="center" />
                        <el-table-column prop="alarmScore" label="故障告警总分" width="120" fixed="right" align="center" />
                      </el-table>
                    </div>
                    <div class="card-right">
                      <div class="title-name">分数趋势:</div>
                      <div
                        id="lineChart"
                        style="width: 620px; height: 320px; margin: -10px 20px 20px 40px"
                        class=""
                        ref="lineChart"
                        v-show="!showAll"
                      ></div>
                      <div class="data-analyse">
                        <div class="analyse-title">数据分析：</div>
                        <div class="analyse-itemlist">
                          <div class="analyse-item">
                            <a>所选时间：{{ selectedDays }}天</a>
                          </div>
                          <div class="analyse-item">
                            <a>故障告警平均分：{{ averageScore.toFixed(2) }}分</a>
                          </div>
                          <div class="analyse-item">
                            <a>所选时间内最高分：{{ maxScore }}分</a>
                          </div>
                          <div class="analyse-item">
                            <a>所选时间内最低分:{{ minScore }}分</a>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
            </el-card>
        </el-dialog>

    </div>

</template>

<script setup name="networkAlarm">

import { queryAlarm4gResultList, queryAlarm5gResultList, queryRealTimeAlarmList, queryHistoryAlarmList , detailList } from '@/api/biz/networkAlarm';
import * as echarts from 'echarts';
import { ref } from 'vue';

const { proxy } = getCurrentInstance();
const { nhp_county_type, nhp_network_type } = proxy.useDict("nhp_county_type", "nhp_network_type");

var currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 1);

const queryParams = ref({
    networkType: "5G",
    createStartEnd: [new Date(), currentDate]
})

const tableData = ref([])
const realTimeAlarmTableData = ref([])
const historyAlarmTableData = ref([])
const detailTableData = ref([])

const pageSize = ref(10)
const currentPage = ref(1)
const total = ref(0)

const realPageSize = ref(10)
const realCurrentPage = ref(1)
const realTotal = ref(0)

const historyPageSize = ref(10)
const historyCurrentPage = ref(1)
const historyTotal = ref(0)

const alarmDialogTableVisible = ref(false)
const detailTableVisible = ref(false)


const activeName = ref('realTimeAlarm')

const currentStationNo = ref("");

const nowOrder = ref();
const nowStatus = ref();

const chart1 = ref(null);
const chart2 = ref(null);
let chartInstance1 = null;
let chartInstance2 = null;

const levelTemp1 = ref([]);
const levelTemp2 = ref([]);
const realTimeAlarmLevel = ref();
const pastAlarmLevel = ref();

const detailDatePicker = ref('');
const end = new Date();
const start  = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
detailDatePicker.value = [start,end];

const detailData = ref([])
const currNetworkType = ref()

// 重置
function unsetQueryForm(){
    queryParams.value = {
        networkType: "5G",
        county:"",
        stationNo:"",
        stationName:"",
        createTime: [],
    }
}

function fnalarmLevel(levelNum){
    if(levelNum === 1){
        return "danger";
    }else if(levelNum === 2){
        return "warning";
    }else if(levelNum === 3){
        return "primary";
    }else if(levelNum === 4){
        return "success";
    }
}

// 导出
function exportData() {
    const param = {};
    param.networkType = queryParams.value.networkType;
    param.county = queryParams.value.county;
    param.stationNo = queryParams.value.stationNo;
    param.stationName = queryParams.value.stationName;
    if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
        param.createStart = queryParams.value.createStartEnd[0].toLocaleDateString()
        param.createEnd = queryParams.value.createStartEnd[1].toLocaleDateString()
    }
    param.sortContent = "alarmScore";
    param.order = nowOrder.value;
    param.status = nowStatus.value;
    proxy.download("/networkAlarm/exportAlarmList", {
        ...param
    }, `故障告警_${new Date().getTime()}.xlsx`);
}


function listAlarmTable() {
    const param = {}
    param.pageSize = pageSize.value;
    param.pageNum = currentPage.value;
    param.county = queryParams.value.county;
    param.stationName = queryParams.value.stationName;
    param.stationNo = queryParams.value.stationNo;
    param.order = nowOrder.value;
    param.status = nowStatus.value;
    if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
        param.createStart = queryParams.value.createStartEnd[0].toLocaleDateString();
        param.createEnd = queryParams.value.createStartEnd[1].toLocaleDateString();
    }
    if (queryParams.value.networkType == "5G") {
        //加载5G结果
        queryAlarm5gResultList(param).then(res => {
            currNetworkType.value = "5G"
            tableData.value = res.rows;
            total.value = res.total;
        })
    } else if (queryParams.value.networkType == "4G") {
        //加载4G结果
        queryAlarm4gResultList(param).then(res => {
            currNetworkType.value = "4G"
            tableData.value = res.rows;
            total.value = res.total;
        })
    }
}

async function showAlarmDialog(stationNo) {
    alarmDialogTableVisible.value = true;
    currentStationNo.value = stationNo;
    //获取告警信息
    let param = {
        stationNo: stationNo
    }
    await queryRealTimeAlarmList(param).then(res1 => {
        realTimeAlarmTableData.value = res1.rows;
        realTimeAlarmTableData.value.forEach(function(item , index){
            levelTemp1.value.push(item.alarmLevel);
        })
        realTotal.value = res1.total;
    })
    await queryHistoryAlarmList(param).then(res2 => {
        historyAlarmTableData.value = res2.rows;
        debugger
        historyAlarmTableData.value.forEach(function(item , index){
            levelTemp2.value.push(item.alarmLevel);
        })
        historyTotal.value = res2.total;
    })
    initChart()
}

function getPieData(levelTemp){
    var tempData  = levelTemp.reduce((accumulator, currentValue) => {  
                    if ([1, 2, 3, 4].includes(currentValue)) {  
                        accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;  
                    }  
                    return accumulator;  
                    }, {});
    return tempData;
}

// 饼状图
function initChart(){
    chartInstance1 = echarts.init(chart1.value);
    chartInstance2 = echarts.init(chart2.value);
    drawChart();
}

function drawChart(){
    realTimeAlarmLevel.value = getPieData(levelTemp1.value);
    pastAlarmLevel.value = getPieData(levelTemp2.value);
    var pieData1 = [
        {
            name:'一级告警',
            value: realTimeAlarmLevel.value[1]
        },{
            name:'二级告警',
            value: realTimeAlarmLevel.value[2]
        },{
            name:'三级告警',
            value: realTimeAlarmLevel.value[3]
        },{
            name:'四级告警',
            value: realTimeAlarmLevel.value[4]
        },
    ];
    var pieData2 = [
        {
            name:'一级告警',
            value: pastAlarmLevel.value[1]
        },{
            name:'二级告警',
            value: pastAlarmLevel.value[2]
        },{
            name:'三级告警',
            value: pastAlarmLevel.value[3]
        },{
            name:'四级告警',
            value: pastAlarmLevel.value[4]
        },
    ];
    var option1 = {
        color: ['#ef6567','#fc8251', '#5470c6', '#91cd77',],
        series:[
            {
                type: 'pie', // 类型： 饼图
                data: pieData1,//数据
                label: {//饼图文字的显示
                    show: true, //默认  显示文字
                    formatter: function (arg) {
                        console.log(arg);
                        return arg.name + ' 有 ' + arg.value + " 条" +'\n'+'占比'+ arg.percent + "%"
                    }
                },
                selectedMode: 'multiple',
                selectedOffset: 30,
                radius: ['50%','80%']
            }
        ]
    };
    var option2 = {
        color: ['#ef6567','#fc8251', '#5470c6', '#91cd77',],
        series:[
            {
                type: 'pie', // 类型： 饼图
                data: pieData2,//数据
                label: {//饼图文字的显示
                    show: true, //默认  显示文字
                    formatter: function (arg) {
                        console.log(arg);
                        return arg.name + ' 有 ' + arg.value + " 条" +'\n'+'占比'+ arg.percent + "%"
                    }
                },
                selectedMode: 'multiple',
                selectedOffset: 30,
                radius: ['50%','80%']
            }
        ]
    };
    chartInstance1.setOption(option1);
    chartInstance2.setOption(option2);
}

// 打开详情页
function showDetailDialog(stationNo) {
    detailTableVisible.value = true;
    currentStationNo.value = stationNo;
    //获取该站点的故障告警历史得分列表
    listDetailTable(currentStationNo.value);
}

// 详情页列表
function listDetailTable(stationNo){
    const param = {};
    param.stationNo = stationNo;
    param.createStart = formatDate(detailDatePicker.value[0]);
    param.createEnd = formatDate(detailDatePicker.value[1]);
    param.networkType = currNetworkType.value
    detailList(param).then(res => {
        detailData.value = res.data;
    })
}

function detailSearch(){
    listDetailTable(currentStationNo.value);
    initLineChart();
}

// 格式化日期
function formatDate(dateString){
    const date = new Date(dateString);  
    const year = date.getFullYear();  
    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 加 1 因为月份是从 0 开始的，并使用 padStart 来确保月份是两位数  
    const day = date.getDate().toString().padStart(2, '0'); // 使用 padStart 来确保日期是两位数  
    return `${year}-${month}-${day}`; 
}

// 折线图
const lineChart = ref(null);
let lineChartInstance = null;

function initLineChart(){
    lineChartInstance = echarts.init(lineChart.value);
    drawLineChart();
    calculateStatistics();
}

function drawLineChart(){
    const xData = detailData.value.map(item => item.createTime); // 创建时间数组  
    const yData = detailData.value.map(item => item.alarmScore); // 网络质量总分数组  

    const options = {  
        tooltip: {
          trigger: "axis",
        },
        grid: {
          left: "5%",
          right: "15%",
          bottom: "10%",
        },
        xAxis: {  
            type: 'category',  
            data: xData,  
        },  
        yAxis: {  
            type: 'value',  
        },  
        series: [{  
            data: yData,  
            type: 'line',  
            smooth: true,  
        }],  
    };  
    lineChartInstance.setOption(options);  
}

const selectedDays = ref(0);
const averageScore = ref(0);
const maxScore = ref(0);
const minScore = ref(0);
function calculateStatistics(){
    const scores = detailData.value.map(item => item.alarmScore);  
    const startDate = new Date(detailDatePicker.value[0]);  
    const endDate = new Date(detailDatePicker.value[1]);  
    const diffTime = endDate - startDate;  
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    selectedDays.value = diffDays+1;
    averageScore.value = scores.reduce((sum, score) => sum + score, 0) / scores.length;
    maxScore.value = Math.max(...scores);  
    minScore.value = Math.min(...scores);
}

function closeAlarmDialog() {
    alarmDialogTableVisible.value = false
    currentStationNo.value = ""
    realTimeAlarmTableData.value = []
    realCurrentPage.value = 1
    realTotal.value = 0
    realPageSize.value = 10

    historyAlarmTableData.value = []
    historyCurrentPage.value = 1
    historyTotal.value = 0
    historyPageSize.value = 10
    activeName.value = "realTimeAlarm";
    levelTemp1.value = [];
    levelTemp2.value = [];
    console.log("alarmDialogTableVisible : "+alarmDialogTableVisible.value);
}

function dateFormatter(row, column, cellValue, index) {
    if (!cellValue) { return }
    // 创建一个新的 Date 对象
    var originalDate = new Date(cellValue);

    // 获取年、月、日、时、分、秒
    var year = originalDate.getFullYear();
    var month = ("0" + (originalDate.getMonth() + 1)).slice(-2);
    var day = ("0" + originalDate.getDate()).slice(-2);
    var hours = ("0" + originalDate.getHours()).slice(-2);
    var minutes = ("0" + originalDate.getMinutes()).slice(-2);
    var seconds = ("0" + originalDate.getSeconds()).slice(-2);

    // 格式化输出
    var formattedDateTimeString = year + "-" + month + "-" + day;
    return formattedDateTimeString;
}


// 总分排序
function sortChange(column, prop, order){
    nowOrder.value = column.order;
    listAlarmTable();
}
// 筛选状态
function filterChange(filters){
    nowStatus.value  = filters.status[0];
    listAlarmTable();
}

listAlarmTable();


</script>

<style>
.card-box {
  padding: 0px;
}
.card-left{
    width: 50%;
}
.title-name{
    justify-content: space-between;
    font-size: 14px;
    font-weight: bold;
}

.card-right{
    margin-left: 20px;
    width: 50%;
    /* border: 1px solid #000; */
}

.data-analyse {
    margin: 10px;
    height: 100px;
    width: 300px;
    .analyse-title {
      height: 50px;
      padding: 10px 10px 0px 10px;
      font-weight: bold;
      font-size: 14px;
    }
    .analyse-itemlist {
      height: 60px;
      width: 600px;
      margin-left: 50px;
      font-size: 14px;
      display: flex;
      flex-wrap: wrap;
    }
    .analyse-item {
      min-width: 300px;
      height: 30px;
      margin: 0px;
      padding: 0px;
      font-size: 15px;
    }
  }

</style>